<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'

import { ElInput } from 'element-plus'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
const data = ref<any>({})
import { UploadLxq } from '@/components/UploadLxq'
import { UploadFileLxq } from '@/components/UploadFileLxq'
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})
const typeChange = (value) => {
  data.value.file_type = value
  console.log(file_name.value, 'file_name.value')
  if (file_name.value) {
    data.value.file_url = ''
    file_name.value = ''
  }
}
const file_name = ref('')
const fileData = ref({})
const onChange = (value) => {
  file_name.value = value.file_name
  fileData.value = value
  data.value.file_name = value.file_name
  const { setValues } = methods
  setValues(data)
}
const onChangeFile = (value) => {
  console.log(value, 'value')
  file_name.value = value.file_name
  fileData.value = value
  data.value.file_name = value.file_name
  const { setValues } = methods
  setValues(data)
}

const schema: any = [
  {
    field: 'customer_name',
    component: 'Input',
    label: '所属牧场',
    componentProps: {
      readonly: true
    }
  },
  {
    field: 'file_type',
    label: '文件类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '图片',
          value: '1'
        },
        {
          label: '文件',
          value: '2'
        }
      ],
      onChange: typeChange
    }
  },
  {
    field: 'file',
    label: '上传文件'
  },
  {
    field: 'file_name',
    label: '文件名称',
    component: 'Input'
  },
  {
    field: 'name',
    label: '文件标题',
    component: 'Input'
  }
]
const rules = reactive({})

const { register, methods, elFormRef } = useForm({
  schema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    console.log(currentRow, 'currentRow')
    currentRow.customer_name = userInfo.default_org_name
    currentRow.customer_id = userInfo.default_org_id
    data.value = currentRow
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  elFormRef,
  getFormData: methods.getFormData,
  fileData,
  file_name
})
</script>

<template>
  <Form :rules="rules" @register="register" :data="data">
    <template #file>
      <UploadLxq v-if="data.file_type == 1" @change="onChange" v-model="data.file_url" />
      <UploadFileLxq @change="onChangeFile" v-else v-model="data.file_url" />
    </template>
    <template #file_name>
      <ElInput v-model="data.file_name" clearable />
    </template>
  </Form>
</template>
